import {Component, OnInit} from '@angular/core';
import {OPERATES} from '../../../../_mock/operate';
import {Globals} from '../../globals';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {ApiUrl} from "../../config/api-url";
import {BaseService} from "../../shared/service/base.service";
import {PageHelper} from "../../utils/page-helper-model";
import {ActivatedRoute, Router} from "@angular/router";
import {RoleIdEnum} from "../../enums/role-id.enum";
import {Consts} from "../../config/consts";
import {UserInfoModel} from "../../models/user-info.model";


@Component({
  selector: 'app-store',
  templateUrl: './store.component.html',
  styleUrls: ['./store.component.less']
})
export class StoreComponent implements OnInit {

  isMobile = Globals.isMobile();
  listOfData: any;
  formModel: FormGroup;
  // 分页
  pageHelper: PageHelper = new PageHelper;
  // 机构
  agencyList: [];
  // 运营商
  userList: [];
  // 门店
  merchantStoreList: [];
  roleIdEnum = {
    SUPER_ADMINISTRATOR: RoleIdEnum.SUPER_ADMINISTRATOR,
    AGENT: RoleIdEnum.AGENT,
    MERCHANT: RoleIdEnum.MERCHANT,
  };
  // 用户信息
  userInfo: UserInfoModel;
  nzVisible = false;
  nzVisibleBind = false;
  // 门店参数
  store: any;
  meiTuanPackageListNew:any;
  freezeReason: any;
  nzLoading: boolean;
  nzVisibleTimeLimit = false;

  discountPackages: any[] = [];

  constructor(private fb: FormBuilder, private baseService: BaseService, private activatedRoute: ActivatedRoute, private router: Router) {
    this.buildForm();
    this.activatedRoute.queryParams.subscribe(params => {
      if (params['userId'] != null) {
        this.formModel.get("userId").setValue(params['userId']);
        this.getAgentsData();
      } else {
        this.getAgentsData();
      }
    });
  }


  ngOnInit(): void {
    this.getAllAgencyOfName();
    this.getAllUserOfName();
    this.findAllMerchantStoreByUserInfo();
    this.userInfo = JSON.parse(sessionStorage.getItem(Consts.USER_INFO));

    this.discountPackages = [
      {name: 1, coin: 1, give: 1,},
      {name: 1, coin: 1, give: 1,},
    ]
  }


  buildForm() {
    this.formModel = this.fb.group({
      agencyId: ['', []],
      userId: ['', []],
      merchantStoreId: ['', []],
      douYinMeiTuanType: ['', []],
      keyword: ['', []],
    });
  }

  submitForm() {
    this.pageHelper.currentPage = 1;
    this.getAgentsData();
  }

// 子传父值
  event(event: any) {
    this.store = event;
  }
  getAgentsData() {
   //this.formModel.value.merchantStoreId = 8419;
    this.baseService.findListByMuchCondition(ApiUrl.MerchantStoreUrl + '/list', this.formModel.value, this.pageHelper).subscribe(
      data => {
        if (data.status == 0) {
          this.pageHelper.totalItems = data.data.total;
          this.listOfData = data.data.list;
          this.listOfData.forEach(res => {
            res.expand = false;
          })
        } else {
          this.baseService.layer.messageError(data.msg);
        }
      }
    );
  }
  onPageSizeChange(pageSize: any){
    this.pageHelper.pageSize = pageSize;
    this.pageHelper.currentPage = 1;
    this.getAgentsData();
  }
  getAllAgencyOfName() {
    this.baseService.get(ApiUrl.AgencyUrl + '/getAllAgencyOfName').subscribe(data => {
      if (data.status == 0) {
        this.agencyList = data.data;
      } else {
        this.baseService.layer.messageError(data.msg);
      }
    });
  }

  getAllUserOfName() {
    let agencyId = this.formModel.get("agencyId").value;
    if (agencyId == null) {
      agencyId = '0';
    }
    this.baseService.get(ApiUrl.UserUrl + '/getAllUserOfName?agencyId=' + agencyId).subscribe(data => {
      if (data.status == 0) {
        this.userList = data.data;
      } else {
        this.baseService.layer.messageError(data.msg);
      }
    });
  }

  findAllMerchantStoreByUserInfo() {
    let userId = null;
    if (this.formModel.get("userId").value != null) {
      userId = this.formModel.get("userId").value
    } else {
      userId = '';
    }
    this.baseService.get(ApiUrl.MerchantStoreUrl + '/findAllMerchantStoreByUserInfo?userId=' + userId).subscribe(
      data => {
        if (data.status == 0) {
          this.merchantStoreList = data.data;
        } else {
          this.baseService.layer.messageError(data.msg);
        }
      }
    );
  }

  gainAgencyId($event: any) {
    this.getAllUserOfName();
  }

  gainUserId($event: any) {
    this.findAllMerchantStoreByUserInfo();
  }

  nzPageIndexChange($event: number) {
    this.pageHelper.currentPage = $event;
    this.getAgentsData();
  }

  skipMerchant(data: any) {
    this.router.navigateByUrl('/merchant?userId=' + data.userId,
      {skipLocationChange: true});
  }

  skipMember(data: any) {
    this.router.navigateByUrl('/user?merchantStoreId=' + data.id,
      {skipLocationChange: true});
  }

  skipDevice(data: any) {
    this.router.navigateByUrl('/device?userId=' + data.userId,
      {skipLocationChange: true});
  }

  skipAgency(data) {
    this.router.navigateByUrl('/agency?agencyNo=' + data.agencyNo,
      {skipLocationChange: true});
  }

  lockUser(store: any, storeStatus, tplContent) {
    let msg = null;
    if (storeStatus == 0) {
      if (store.freezeReason != null) {
        msg = '因' + store.freezeReason + '被冻结，您确定要恢复';
      } else {
        msg = '确定要恢复该场地吗？';
      }
      this.dispose(store, storeStatus, msg);
    } else {
      msg = '确定要冻结该场地吗？';
      this.baseService.layer.createTplModal('请输入冻结原因', tplContent, confirm => {
        if (confirm) {
          if (this.freezeReason == null || this.freezeReason == '') {
            this.baseService.layer.modalError('请输入冻结原因');
            return;
          }
          this.dispose(store, storeStatus, msg);
        }
      });
    }
  }

  dispose(store, merchantStatus, msg) {
    this.baseService.layer.modalConfirm(msg, confirm => {
      if (confirm) {
        this.nzLoading = true;
        const body = {
          id: store.id,
          userId: store.userId,
          status: merchantStatus,
          freezeReason: this.freezeReason,
        };
        this.baseService.put(ApiUrl.MerchantStoreUrl, body).subscribe(data => {
          if (data.status == 0) {
            this.nzLoading = false;
            this.getAgentsData();
          } else {
            this.baseService.layer.messageError(data.msg);
            this.nzLoading = false;
          }
        });
      }
    });
  }

  setStoreBind($event: any) {
    this.nzVisibleBind = false;
    //console.log("进入了吗");
    this.getAgentsData();
  }
  clickQuota(data: any) {
    this.nzVisible = true;
    console.log(data);
    this.store = data;
  }

  setStoreQuota($event: any) {
    this.nzVisible = false;
    this.getAgentsData();
  }

  clickTimeLimit(data: any) {
    this.nzVisibleTimeLimit = true;
    this.store = data;
  }

  setStoreTimeLimit($event: any) {
    this.nzVisibleTimeLimit = false;
    this.getAgentsData();
  }

}
